package com.schoolET.controller.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.schoolET.entity.dto.NewsDTO;
import com.schoolET.entity.vo.AddNewsVO;
import com.schoolET.entity.vo.NewsInfoVO;
import com.schoolET.error.costom.PermissionsException;
import com.schoolET.result.MyPage;
import com.schoolET.result.Result;
import com.schoolET.service.admin.INewsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author: lin
 * @className: NewsManageController
 * @createTime: 2024-06-02  20:10
 * @description: 新闻管理
 */
@Api(tags = "新闻管理")
@RestController
@RequestMapping("/schoolET")
public class NewsManageController {

    @Resource
    private INewsService newsService;

    @ApiOperation(value = "查询新闻")
    @PostMapping("/newList")
    @SaCheckLogin
    @SaCheckRole(mode = SaMode.OR, value = {"admin", "region-admin"})
    public Result newList(NewsInfoVO newsInfo) {
        if (StpUtil.hasPermission("2") && newsInfo.getPosition() != null) {
            throw new PermissionsException();
        }
        if (StpUtil.hasPermission("2")) {
            return Result.success(
                    MyPage.page(newsService.
                            getNewsByAdminId(newsInfo.getPageNum(), newsInfo.getPageSize(), StpUtil.getLoginIdAsInt())))
                    .msg("查询成功");
        }
        Page<NewsDTO> newsList = newsService.getNewsList(newsInfo);
        return Result.success(MyPage.page(newsList)).msg("查询成功");
    }

    @ApiOperation(value = "发布新闻")
    @PostMapping("/newsRele")
    @SaCheckLogin
    @SaCheckRole("region-admin")
    public Result newsRele(AddNewsVO addNewsVO, MultipartFile file) throws IOException {

        newsService.addNews(addNewsVO, StpUtil.getLoginIdAsInt(), file);
        return Result.success().msg("添加成功");
    }

    @ApiOperation(value = "删除新闻")
    @PostMapping("/newsDel/{id}")
    @SaCheckLogin
    @SaCheckRole(mode = SaMode.OR, value = {"admin", "region-admin"})
    public Result newsDel(@PathVariable Integer id) {
        newsService.removeById(id);
        return Result.success().msg("删除成功");
    }


}
